package com.web.boot.web.cms;

import com.blue.core.dict.HttpMethod;
import com.blue.core.dict.annotation.DictParser;
import com.blue.http.annotation.Http;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.View;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.cms.doc.facade.WebFacade;
import com.web.cms.doc.message.WebRequest;
import com.web.cms.doc.message.WebResponse;
import com.web.core.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller("cmsWebController")
@Http(url = "/cms")
public class WebController
{
	@Autowired
	private WebFacade webFacade;
	
	private DictParser dictParser = DictParser.getInstance();
	
	public WebController()
	{
	}
	
	@Http(url = "/web_list", method = HttpMethod.GET)
	public View listGet(HttpRequest request)
	{
		WebRequest webRequest = request.getQueryObject(WebRequest.class);
		return View.createBuilder().setView("/cms/web_list")
				.put("model", webRequest)
				.put("map", dictParser.getStringMap())
				.put("page", webFacade.listPage(webRequest, Const.PAGE_START, Const.PAGE_SIZE))
				.build();
	}
	
	@Http(url = "/web_list", method = HttpMethod.POST)
	public View listPost(HttpRequest request)
	{
		WebRequest webRequest = request.getPostObject(WebRequest.class);
		int start = request.getPostInt("start", Const.PAGE_START);
		return View.createBuilder().setView("/cms/web_list_grid")
				.put("page", webFacade.listPage(webRequest, start, Const.PAGE_SIZE))
				.build();
	}
	
	@Http(url = "/web_get", method = HttpMethod.GET)
	public View get(HttpRequest request)
	{
		int id = request.getQueryInt("id", 0);
		WebResponse response = null;
		if (id > 0)
		{
			response = webFacade.get(id);
		}
		return View.createBuilder().setView("/cms/web_get")
				.put("model", response == null ? new WebResponse() : response)
				.put("map", dictParser.getStringMap())
				.build();
	}
	
	@Http(url = "/web_save", method = HttpMethod.POST)
	public void save(HttpRequest request)
	{
		WebRequest webRequest = request.getPostObject(WebRequest.class);
		if (webRequest.getId() == null)
		{
			ValidationUtil.valid(webRequest, SaveModel.class);
			webFacade.add(webRequest);
		}
		else
		{
			ValidationUtil.valid(webRequest, UpdateModel.class);
			webFacade.update(webRequest);
		}
	}
	
	@Http(url = "/web_refresh", method = HttpMethod.POST)
	public void refresh(HttpRequest request)
	{
		webFacade.refresh();
	}
	
}
